package huawei;

import java.util.LinkedList;

/**
 * @author Wenhao Tong
 * @create 2021-07-31 9:48
 */
public class Main {
    public static void main(String[] args) {
        System.out.println("()[]{}:" + valid("()[]{}"));
        System.out.println("(]:" + valid("(]"));
        System.out.println("{()}({}):" + valid("{()}({})"));
        System.out.println("{{}[]()}:" + valid("{{}[]()}"));
        System.out.println("(())()():" + valid("(())()()"));
        System.out.println("(()[)]():" + valid("(()[)]()"));
    }
    public static boolean valid(String str) {
        LinkedList<Character> stack = new LinkedList<>();
        for (int i = 0;i < str.length();i++) {
            if (str.charAt(i) == '(') {
                stack.push(str.charAt(i));
            } else if (str.charAt(i) == '[') {
                if (stack.size() > 0 && stack.peek() == '(') {
                    return false;
                }
                stack.push(str.charAt(i));
            } else if (str.charAt(i) == '{') {
                if (stack.size() > 0 && (stack.peek() == '(' || stack.peek() == '[')) {
                    return false;
                }
                stack.push(str.charAt(i));
            } else if (str.charAt(i) == ')') {
                if (stack.size() > 0 && (stack.peek() == '(')) {
                    stack.pop();
                } else {
                    return false;
                }
            } else if (str.charAt(i) == ']') {
                if (stack.size() > 0 && stack.peek() == '[') {
                    stack.pop();
                } else {
                    return false;
                }
            } else {
                if (stack.size() > 0 && stack.peek() == '{') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        if (stack.size() == 0) {
            return true;
        }
        return false;
    }
}
